#include <iostream>
#include "ObjectPool.h"
#include <vector>
#include <chrono>
#include <ctime>

using std::vector;

struct TreeNode
{
	int _val;
	TreeNode* _left;
	TreeNode* _right;

	TreeNode()
		:_val(0)
		, _left(nullptr)
		, _right(nullptr)
	{}
};

void test1()
{
  vector<TreeNode *> vec;

  // auto start = std::chrono::steady_clock::now();
  std::time_t start = std::time(nullptr);

  for(int j = 0; j < 5; j++){

  for(int i{}; i < 1000000; i++){
    vec.push_back(new TreeNode);
  }

  for(int i{}; i < 1000000; i++){
    delete vec[i]; 
  }

  vec.clear();

  }
  // auto finish = std::chrono::steady_clock::now();
  
  
  // std::chrono::duration<double> dur = finish - start;
  cout << "cost time: " << std::difftime(std::time(nullptr), start) << endl;
  // printf("---------------end-------------\n", dur.count());
}

void test()
{
  ObjectPool<int> op;
  // int *ip = op.New();
  // op.Delete(ip);
  vector<int *> vec(1000000);

  // auto start = std::chrono::steady_clock::now();
  std::time_t start = std::time(nullptr);

  for(int j = 0; j < 3; j++){

  for(int i{}; i < 1000000; i++){
    vec.push_back(op.New()); 
  }

  for(int i{}; i < 1000000; i++){
    op.Delete(vec[i]); 
  }

  }
  // auto finish = std::chrono::steady_clock::now();
  
  
  // std::chrono::duration<double> dur = finish - start;
  cout << "cost time: " << std::difftime(std::time(nullptr), start) << endl;
  // printf("---------------end-------------\n", dur.count());
}

void test3()
{
  // 申请释放的轮次
	const size_t Rounds = 20;

	// 每轮申请释放多少次
	const size_t N = 100000;

	std::vector<TreeNode*> v1;
	v1.reserve(N);

	// size_t begin1 = clock();
  // std::time_t begin1 = std::time(nullptr);
  auto start1 = std::chrono::high_resolution_clock::now();
	for (size_t j = 0; j < Rounds; ++j)
	{
		for (int i = 0; i < N; ++i)
		{
			v1.push_back(new TreeNode);
		}
		for (int i = 0; i < N; ++i)
		{
			delete v1[i];
		}
		v1.clear();
	}

  auto stop1 = std::chrono::high_resolution_clock::now();
	cout << "new cost time:" << std::chrono::duration_cast<std::chrono::milliseconds>(stop1 - start1).count() << endl;

	std::vector<TreeNode*> v2;
	v2.reserve(N);

	ObjectPool<TreeNode> TNPool;
  // std::time_t begin2 = std::time(nullptr);
  auto start2 = std::chrono::high_resolution_clock::now();
	for (size_t j = 0; j < Rounds; ++j)
	{
		for (int i = 0; i < N; ++i)
		{
			v2.push_back(TNPool.New());
		}
		for (int i = 0; i < N; ++i)
		{
			TNPool.Delete(v2[i]);
		}
		v2.clear();
	}

  auto stop2 = std::chrono::high_resolution_clock::now();
	cout << "object pool cost time:" << std::chrono::duration_cast<std::chrono::milliseconds>(stop2 - start2).count() << endl;
  
	// cout << "object pool cost time:" << std::difftime(std::time(nullptr), begin2) << endl;
}

int main()
{
  test3();
}
